<template>
  <div class="container">
    <h1>注册</h1>
    <div class="row">
      <div class="col-md-4">
        <form @submit.prevent="onSubmit">
          <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" class="form-control" id="username" v-model="username"
                   v-bind:class="{'is-invalid': usernameError}">
            <div v-show="usernameError" class="invalid-feedback">{{ usernameError }}</div>
          </div>

          <div class="form-group">
            <label for="email">邮箱</label>
            <input type="email" class="form-control" id="email"
                   v-model="email" aria-describedby="emailHelp" v-bind:class="{'is-invalid': emailError}">
            <div v-show="emailError" class="invalid-feedback">{{ emailError }}</div>
          </div>

          <div class="form-group">
            <label for="password">密码</label>
            <input type="password" class="form-control" v-model="password"
                   v-bind:class="{'is-invalid': passwordError}" id="password">

            <!--v-show 根据条件展示元素，类似于 v-if，若 passwordError 为真，则显示 div 元素，即展示错误信息-->
            <div v-show="passwordError" class="invalid-feedback">{{ passwordError }}</div>
          </div>

          <button type="submit" class="btn btn-primary">注册</button>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
  import axios from 'axios'
  import store from '../store.js'

  export default {
    name: "Register",
    data() {
      return {
        username: '',
        email: '',
        password: '',
        submitted: false, // 是否点击 submit 按钮
        errors: 0,
        usernameError: null,
        emailError: null,
        passwordError: null
      }
    },
    methods: {
      onSubmit(e) {
        this.submitted = true;  // 先更新状态
        this.errors = 0;

        // 判断输入框是否为空
        if (!this.username) {
          this.errors++;
          this.usernameError = "用户名不能为空！"
        } else {
          this.usernameError = null
        }

        if (!this.email) {
          this.errors++;
          this.emailError = "邮箱不能为空！"
        } else if (!this.validEmail(this.email)) {
          this.errors++;
          this.emailError = "请输入一个有效的邮箱地址！"
        } else {
          this.emailError = null
        }

        if (!this.password) {
          this.errors++;
          this.passwordError = "密码不能为空！"
        } else {
          this.passwordError = null
        }

        // 若有错误，则跳出，不能往下执行
        if (this.errors > 0) {
          return false;
        }

        // 请求
        const url = "/users";
        const payload = {
          username: this.username,
          email: this.email,
          password: this.password
        };

        axios.post(url, payload)
          .then((resp) => {
            // 更新状态，提示用户
            store.setNewAction();

            // 跳转到登录
            this.$router.push('/login')
          })
          .catch((error) => {
            for (var field in error.response.data.message) {
              if (field === 'username') {
                this.usernameError = error.response.data.message.username;
              } else if (field === 'email') {
                this.emailError = error.response.data.message.email;
              } else if (field === 'password') {
                this.passwordError = error.response.data.message.password;
              }
            }
          })
      },

      // 验证邮箱地址是否合法
      validEmail: function (email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
      }
    }
  }
</script>

<style scoped>

</style>
